<template>
    <div class="layout-parent w100 p10">
        <el-tabs type="border-card">
            <el-tab-pane>
                <template #label><vp-label zh="基本信息" en="Basic Info"/></template>
                <div v-loading="loading">
                    <AbnormalMaintenance type="audit" ref="abnormalMaintenanceRef" />
                    <vp-card>
                        <template #header><vp-label zh="事件补充描述" en="Incident Supplementary Description"/></template>
                        <AbnormalMaintenanceSupplement type="audit" ref="abnormalSupplementRef" />
                    </vp-card>
                    <vp-card>
                        <template #header><vp-label zh="创建事件清单" en="Create Incident List"/></template>
                        <el-form ref="processExtFormRef" label-suffix=":" :model="processExtFormData" label-width="140px" class="w100">
                            <el-row v-if="isPass">
                                <vp-col :span="2" >
                                    <el-form-item prop="leaderName">
                                        <template #label><vp-label zh="手机提醒（领导）" en="Phone Rem. (Leader)"/></template>
                                        <el-input readonly v-model="leaderName">
                                            <template #append>
                                                <el-button @click="handleSearchPhoneNotice"><SvgIcon name="ele-Search"/></el-button>
                                            </template>
                                        </el-input>
                                    </el-form-item>
                                </vp-col>
                                <vp-col :span="1" >
                                    <el-form-item prop="sjqdbs" :rules="[validateUtils.notNull]">
                                        <template #label><vp-label zh="创建事件清单" en="Create Incident List"/></template>
                                        <el-radio-group  v-model="processExtFormData.sjqdbs">
                                            <el-radio :label="1"><vp-label zh="是，创建新的不正常事件清单信息" en="Yes, create new abnormal incident list information"/></el-radio>
                                            <el-radio :label="2"><vp-label zh="否，选择已有的事件清单建立关联" en="No, select existing incident list to establish association"/></el-radio>
                                            <el-radio :label="3"><vp-label zh="否，不创建也不关联" en="No, neither create nor associate"/></el-radio>
                                        </el-radio-group> 
                                    </el-form-item>
                                </vp-col>
                                <vp-col :span="1" v-if="processExtFormData.sjqdbs === 2">
                                    <el-form-item prop="bzcsjqdid" :rules="[validateUtils.notNull]">
                                        <template #label><vp-label zh="建立事件清单关联" en="Est. Incid. Assoc."/></template>
                                        <el-space>
                                            <el-link type="info" v-if="processExtFormData.bzcsjqdid" @click="handleViewList(processExtFormData.bzcsjqdid)">
                                                <span>{{ processExtFormData.bzcsjqdbh + ": "  + (processExtFormData.bzcsjqdsjjg || '')}}</span>
                                            </el-link>
                                            <el-button type="primary" @click="handleChooseAssociation" plain round size="small">
                                                <el-icon class="mr4"><ele-Search/></el-icon> <span>选择 Choose</span>
                                            </el-button>
                                        </el-space>
                                    </el-form-item>
                                </vp-col>
                            </el-row>
                        </el-form>
                    </vp-card>
                </div>
                <vp-card id="createEventManifestCard" v-show="isPass && processExtFormData.sjqdbs === 1">
                    <template #header><vp-label zh="创建事件清单" en="Create Incident List"/></template>
                    <AbnormalList ref="abnormalListRef" />
                </vp-card>
            </el-tab-pane>
            <el-tab-pane>
                <template #label><vp-label zh="流程记录" en="Process Record"/></template>
                <ProcessHistory :processInsId="processInsId"/>
            </el-tab-pane>
            <el-tab-pane>
                <template #label><vp-label zh="流程图" en="Process Chart"/></template>
                <ProcessView :processInsId="processInsId"/>
            </el-tab-pane>
        </el-tabs>
        <StatusBar
            :id="formData.id"
            :status="formData.zt"
            :isValid="formData.yxbs"
        />
        <PageBottom>
            <VpProcessToolBar 
                label-width="140px"
                :process-ins-id="processInsId" 
                :task-id="taskId" 
                :loading="submitLoading" 
                :before-show-fn="beforeShowFn"
                :after-agree-fn="afterAgreeFn"
                :set-loading-fn="(_loading: boolean) => { submitLoading = _loading }"
                :reject-last-node="true"
            />
        </PageBottom>
        <UserDialog ref="userDialogRef"></UserDialog>
        <ChooseAssociatedList ref="chooseAssociatedRef" @confirm="handleAssociationConfirm"></ChooseAssociatedList>
    </div>
</template>
<script lang="ts">
import { defineComponent, getCurrentInstance, nextTick, onMounted, reactive, ref, toRefs, computed } from 'vue'
import ProcessHistory from '/@/components/vp/workflow/ProcessHistory.vue';
import ProcessView from '/@/components/vp/workflow/ProcessView.vue';
import ProcessHandle from "/@/components/vp/workflow/VpProcessHandle.vue";
import request from '/@/utils/request';
import { useRoute } from 'vue-router';
import { ElMessage } from 'element-plus';
import PageBottom from '/@/components/vp/PageBottom/index.vue';
import AbnormalMaintenance from '../details/AbnormalMaintenance.vue';
import validateUtils from '/@/utils/validateUtils';
import UserDialog from '/@/components/vp/user/VpUserDialog.vue';
import ChooseAssociatedList from '../dialogs/ChooseAssociatedList.vue';
import { useRouter } from 'vue-router';
import AbnormalList from '../details/AbnormalList.vue';
import AbnormalMaintenanceSupplement from '../details/AbnormalSupplement.vue';
import mittBus from '/@/utils/mitt';
import StatusBar from '/@/components/vp/status/StatusBar.vue';
import VpProcessToolBar from '/@/components/vp/workflow/VpProcessToolBar.vue';

export default defineComponent({
    name:'audit4EndAbnormalMaintenanceSupplement',
    props: {
        businessId: String,
        taskId: String,
        processInsId: String,
    },
    components: { ProcessHistory, ProcessView, ProcessHandle, PageBottom, AbnormalMaintenance, UserDialog, 
        ChooseAssociatedList, AbnormalList, AbnormalMaintenanceSupplement, StatusBar, VpProcessToolBar },
    setup(props) {
        const state = reactive({
            loading: false,
            submitLoading: false,
            isPass: true,
            formData: {
                id: "",
                zt: 10,
                yxbs: 1,
                sjbb: 1,
                jdid: '',
            },
            processExtFormData: {
                leaders: [],
                sjqdbs : null,
                bzcsjqdid: '',
                bzcsjqdbh: '',
                bzcsjqdsjjg: '',
                xbcms: null,
                bcr: '',
                bcrid: '',
            },
		});

        const { proxy } = getCurrentInstance() as any;
        const route = useRoute();
        const processHandleRef = ref();
        const abnormalMaintenanceRef = ref();
        const userDialogRef = ref();
        const processExtFormRef = ref();
        const chooseAssociatedRef = ref();
        const router = useRouter();
        const abnormalListRef = ref();
        const abnormalSupplementRef = ref();

        onMounted(() => {
            loadForm();
        });

        const loadForm = () => {
            state.loading = true;
            nextTick(() => {
                request.get(`/abnormal/maintenance/${props.businessId}`).then((res)=>{
                    abnormalMaintenanceRef.value.setData({
                        ...res.data
                    });
                    abnormalSupplementRef.value.setData(res.data.addition);   
                    abnormalListRef.value.setData({
                        jdid: res.data.jdid,
                        sjrq: res.data.sfrq,
                        fjid: res.data.fjid,
                        fjzch: res.data.fjzch,
                        fjjx: res.data.fjjx,
                        sjjg: res.data.sjms,
                        clff: res.data.clqk,
                        sfdmc: res.data.sfdd,
                        sfdid: res.data.sfdid,
                        sfdlx: res.data.sfdlx,
                        fsjd: res.data.sfjds ? res.data.sfjds[0]: ''
                    });
                    state.processExtFormData.bcrid = res.data.cjrid;
                    state.processExtFormData.bcr = res.data.cjr;
                    state.formData = { ...res.data };
                    state.loading = false;
                })
            })
        };

        /**
         * 选择手机提醒（领导）
         */
        const handleSearchPhoneNotice = ()=>{
            userDialogRef.value.handleOpen({
                type: 1,
                multi: true,
                selected: state.processExtFormData.leaders.map((user: any) => {return user.ykdaid}),
                callback: (list: any) => {
                    state.processExtFormData.leaders = list;
                }
            });
		}
        const handleSearchBcr = ()=>{
            userDialogRef.value.handleOpen({
                type: 1,
                multi: false,
                selected: state.processExtFormData.bcrid,
                callback: (data: any) => {
                    state.processExtFormData.bcrid = data.yhid;
                    state.processExtFormData.bcr = data.xm;
                }
            });
		}

        const leaderName = computed(() => {
            return state.processExtFormData.leaders.map((p: any) => { return p.xm;}).join(",");
        })

        const handleOperateChange = (flag:boolean) => {
            state.isPass = flag;
        }

        const handleChooseAssociation = () => {
            chooseAssociatedRef.value.handleOpen({
                selectedId: state.processExtFormData.bzcsjqdid,
            });
        }

        const handleAssociationConfirm = (data: any) => {
            state.processExtFormData.bzcsjqdid = data.id || '';
            state.processExtFormData.bzcsjqdbh = data.bh || '';
            state.processExtFormData.bzcsjqdsjjg = data.sjjg || '';
		}

        const handleViewList = (id: string) => {
            router.push({
				name: "viewAbnormalList",
				params: {
					id: id,
				},
			})
        }

        //同意前操作
        const beforeShowFn = () => {
            state.submitLoading = true;
            const promise1 = processExtFormRef.value.validate();
            const promise2 = state.processExtFormData.sjqdbs === 1 ? abnormalListRef.value.validate() : null;
            return Promise.all([promise1, promise2]).finally(()=>{state.submitLoading = false;});
        }

        //同意后操作
        const afterAgreeFn = (processHandle: any) => { 
            state.submitLoading = true;
            request.post("/abnormal/maintenance/supplement/audit4End", {
                id: abnormalSupplementRef.value.getData().id,
                sjbb: abnormalSupplementRef.value.getData().sjbb,
                processHandle: {
                    processInsId: props.processInsId,
                    taskId: props.taskId,
                    ...processHandle,
                },
                notices: (state.processExtFormData.leaders || []).map((user: any) => {
                    return {
                        userid: user.yhid,
                    }
                }),
                sjqdbs: state.processExtFormData.sjqdbs,
                bzcsjqdid: state.processExtFormData.sjqdbs === 2 ? state.processExtFormData.bzcsjqdid : null,
                eventManifest: state.processExtFormData.sjqdbs === 1 ? abnormalListRef.value.getData() : null,
            }).then(()=>{
                mittBus.emit('onCurrentContextmenuClick', Object.assign({}, { contextMenuClickId: 1, ...route }));
                ElMessage.success("办理完毕/Completed Processing");
            }).catch(()=>{
            }).finally(()=>{
                state.submitLoading = false;
            })
        }

        return {
            ...toRefs(state),
            processHandleRef,
            abnormalMaintenanceRef,
            validateUtils,
            userDialogRef,
            handleSearchPhoneNotice,
            leaderName,
            processExtFormRef,
            handleOperateChange,
            chooseAssociatedRef,
            handleChooseAssociation,
            handleAssociationConfirm,
            handleViewList,
            abnormalListRef,
            handleSearchBcr,
            abnormalSupplementRef,
            beforeShowFn,
            afterAgreeFn,
        }
    },
})
</script>